/**
 * 网络请求调试工具
 * 用于监控和分析API请求，帮助发现重复请求问题
 */

interface RequestInfo {
  url: string;
  method: string;
  timestamp: number;
  params?: any;
  data?: any;
}

class RequestDebugger {
  private requests: RequestInfo[] = [];
  private enabled: boolean = process.env.NODE_ENV === 'development';

  /**
   * 记录请求
   */
  logRequest(url: string, method: string, params?: any, data?: any) {
    if (!this.enabled) return;

    const requestInfo: RequestInfo = {
      url,
      method: method.toUpperCase(),
      timestamp: Date.now(),
      params,
      data,
    };

    this.requests.push(requestInfo);

    // 检查是否有重复请求
    this.checkDuplicateRequests(requestInfo);

    // 保持最近100个请求记录
    if (this.requests.length > 100) {
      this.requests = this.requests.slice(-100);
    }
  }

  /**
   * 检查重复请求
   */
  private checkDuplicateRequests(currentRequest: RequestInfo) {
    const recentRequests = this.requests.filter(
      req => 
        req.url === currentRequest.url &&
        req.method === currentRequest.method &&
        currentRequest.timestamp - req.timestamp < 1000 // 1秒内
    );

    if (recentRequests.length > 1) {
      console.warn(
        `🚨 检测到重复请求:`,
        {
          url: currentRequest.url,
          method: currentRequest.method,
          count: recentRequests.length,
          timestamps: recentRequests.map(req => new Date(req.timestamp).toISOString()),
          params: currentRequest.params,
        }
      );
    }
  }

  /**
   * 获取请求统计
   */
  getRequestStats() {
    if (!this.enabled) return null;

    const stats = this.requests.reduce((acc, req) => {
      const key = `${req.method} ${req.url}`;
      acc[key] = (acc[key] || 0) + 1;
      return acc;
    }, {} as Record<string, number>);

    return {
      totalRequests: this.requests.length,
      uniqueEndpoints: Object.keys(stats).length,
      requestCounts: stats,
      recentRequests: this.requests.slice(-10),
    };
  }

  /**
   * 清除请求记录
   */
  clear() {
    this.requests = [];
  }

  /**
   * 启用/禁用调试
   */
  setEnabled(enabled: boolean) {
    this.enabled = enabled;
  }
}

// 创建全局实例
export const requestDebugger = new RequestDebugger();

// 在开发环境下暴露到window对象，方便调试
if (process.env.NODE_ENV === 'development') {
  (window as any).requestDebugger = requestDebugger;
}
